package com.ai.dmc.utils.visit;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.ai.dmc.utils.encryption.DES;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

import com.ai.dmc.utils.properties.PropertiesUtil;


/**
 * 登录过滤
 * 
 * @author weitao
 */
public class AccessAuthority extends OncePerRequestFilter {
	private String accessRestricted = PropertiesUtil.getString("accessRestricted");
	private String startTime = PropertiesUtil.getString("startTime");
	private String endTime = PropertiesUtil.getString("endTime");

	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
		try {
			String newAce = DES.decrypt(accessRestricted);
			String newSta=DES.decrypt(startTime);
			String newEnd=DES.decrypt(endTime);
			String url = request.getRequestURL().toString();
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
			Date startDate = df.parse(newSta);
			Date endDate = df.parse(newEnd);
			String[] notFilter = new String[] { ".html","!execute" };
			boolean doFilter = false;
			for (String s : notFilter) {
				if (url.indexOf(s) != -1) {
					// 如果uri中包含过滤的uri，则进行过滤
					doFilter = true;
					break;
				}
			}
			if(doFilter && Boolean.parseBoolean(newAce)){
				Date date= new Date();
				if(date.getTime() < startDate.getTime() 
						|| date.getTime() > endDate.getTime()){
					response.sendRedirect("404");
					return;
				}
			}
			filterChain.doFilter(request, response);
		} catch (Exception e1) {
//			logger.error("解码失败");
			filterChain.doFilter(request, response);
		}
	}

}
